package com.sanjin.filter;

import com.sanjin.entity.Admin;
import com.sanjin.repository.AdminRepository;
import com.sanjin.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description: jwt认证filter，进行admin(后台管理员)认证
 * @author: sanjin
 * @date: 2019/5/4 18:49
 */
@Component
public class JwtAuthenticationAdminFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private AdminRepository adminRepository;

    /**
     * token 过滤器，如果请求头中包含token，则进行token认证.
     * <p>
     * 此处校验2种角色，ROLE_ADMIN(后台管理员)/ROLE_WXUSER(微信小程序用户)
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {
        String requestToken = request.getHeader(jwtUtils.getHeader());
        String requestUsername = jwtUtils.getUsernameFromToken(requestToken);
        Admin admin = adminRepository.findByUsername(requestUsername);
        // token 没过期
        if (admin != null && requestToken != null && jwtUtils.validateToken(requestToken, admin.getUsername())) {
            if (SecurityContextHolder.getContext().getAuthentication() == null) {
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                        admin.getUsername(),
                        admin.getPassword(),
                        admin.getAuthorities()
                );
                // 设置 details 信息，包含 sessionId，请求IP等详细信息
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request, response);
    }
}
